package com.snowcattle.game.common.util;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

/**
 * 使用JAXB操作XML的工具类
 */
public class JAXBUtil {

    public static void write(Object xmlObject, Writer writer, boolean fragment) {
        JAXBContext jaxbContext = null;
        try {
            jaxbContext = JAXBContext.newInstance(xmlObject.getClass());
            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
                    Boolean.TRUE);
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, fragment);
            marshaller.marshal(xmlObject, writer);
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
            }
        }
    }

    public static <T> T read(Class<T> xmlObjectClass, String xmlPath) {
        JAXBContext jaxbContext = null;
        Reader reader = null;
        try {
            reader = new FileReader(xmlPath);
            jaxbContext = JAXBContext.newInstance(xmlObjectClass);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            return (T) unmarshaller.unmarshal(reader);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
            }
        }
    }
}
